import { Injectable } from '@nestjs/common';
import { CreateArticleDto } from 'src/dto/create-article.dto';
import { UpdateArticleDto } from 'src/dto/update-article.dto';
import { Article } from 'src/entity/article.entity';
import { QueryArticleDto } from 'src/dto/query-article.dto';
import { parseQueryParams } from 'src/common/utils';
import { join } from 'path';

const fs = require('fs');
const { SitemapStream, streamToPromise } = require('sitemap');
const { createGzip } = require('zlib');
const { Readable } = require('stream');

@Injectable()
export class ArticleService {
  async create(createArticleDto: CreateArticleDto) {
    createArticleDto.seoKeywords = this.parseSeoKeywords(
      createArticleDto.seoKeywords,
    );

    let article = await Article.save({
      ...createArticleDto,
    });
    return article;
  }

  parseSeoKeywords(seoKeywords: string) {
    if (seoKeywords) {
      return seoKeywords.replaceAll(',', '-').replaceAll(' ', '-');
    }
  }

  async findAll(pageNum: number, pageSize: number) {
    const [list, count] = await Article.findAndCount({
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
      order: {
        createTime: 'DESC',
      },
    });

    return { list, count };
  }

  async query(query: QueryArticleDto) {
    let qeryBuilder = Article.createQueryBuilder('article');

    let { queryClone, pageNum, pageSize } = parseQueryParams(query, []);

    qeryBuilder.where(queryClone);

    qeryBuilder.skip((pageNum - 1) * pageSize);
    qeryBuilder.take(pageSize);
    qeryBuilder.orderBy('article.createTime', 'DESC');

    let [list, count] = await qeryBuilder.getManyAndCount();

    return { list, count };
  }

  findOne(id: number) {
    return Article.findOneBy({ id });
  }

  async update(id: number, updateArticleDto: UpdateArticleDto) {
    updateArticleDto.seoKeywords = this.parseSeoKeywords(
      updateArticleDto.seoKeywords,
    );

    return Article.update(id, { ...updateArticleDto });
  }

  remove(id: number) {
    return Article.update(id, { deleteTime: new Date() });
  }
}
